﻿//https://leetcode.cn/problems/maximum-width-of-binary-tree/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root)
    {
        unsigned int ret = 0;
        vector<pair<TreeNode*, unsigned int>> t;
        if (root == nullptr) return 0;
        t.push_back({ root,1 });

        while (t.size())
        {
            auto [x1, y1] = t[0];
            auto [x2, y2] = t.back();

            ret = max(ret, y2 - y1 + 1);

            vector<pair<TreeNode*, unsigned int>> temp;
            for (auto& [a, b] : t)
            {
                if (a->left) temp.push_back({ a->left,2 * b });
                if (a->right) temp.push_back({ a->right,2 * b + 1 });
            }

            t = temp;
        }

        return ret;
    }
};